<route lang="json5">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '检测认证 - 公示详情',
  },
}
</route>

<script lang="ts" setup>
import { useQuery } from '@tanstack/vue-query'
import {
  userCenterGetProductQueryOptions,
  useUserCenterFavoriteMutation,
} from '@/service/app/userCenter.vuequery'

defineOptions({
  name: 'ProductDetail',
})

// 获取页面参数
const productId = ref<number>(0)

// 本地收藏状态，用于即时UI反馈
const isFavoriteLocal = ref<boolean>(false)

onLoad((options) => {
  if (options && options.id) {
    productId.value = Number(options.id)
  }
  else {
    uni.showToast({
      title: '缺少产品ID参数',
      icon: 'error',
    })
  }
})

// 获取产品详情
const {
  data: productDetail,
  isLoading,
  error,
  refetch,
} = useQuery(
  computed(() =>
    userCenterGetProductQueryOptions({
      params: { productId: productId.value },
    }),
  ),
)

// 监听productId变化，重新获取数据
watch(productId, (newId) => {
  if (newId > 0) {
    refetch()
  }
})

// 监听产品详情数据变化，同步本地收藏状态
watch(
  productDetail,
  (newDetail) => {
    if (newDetail?.data) {
      const serverFavoriteStatus = newDetail.data.isFavorite || false
      console.log('服务器收藏状态:', serverFavoriteStatus)
      console.log('当前本地状态:', isFavoriteLocal.value)

      // 只有当服务器状态与本地状态不同时才更新
      if (isFavoriteLocal.value !== serverFavoriteStatus) {
        console.log('同步服务器状态到本地')
        isFavoriteLocal.value = serverFavoriteStatus
      }
    }
  },
  { immediate: true },
)

// 收藏功能
const { mutate: addFavorite } = useUserCenterFavoriteMutation({
  onSuccess: (data) => {
    console.log('收藏操作成功:', data)
    console.log('操作前状态:', isFavoriteLocal.value)

    // 验证API响应是否真的成功
    if (data?.success) {
      // 立即更新本地状态，提供即时视觉反馈
      isFavoriteLocal.value = !isFavoriteLocal.value
      console.log('操作后状态:', isFavoriteLocal.value)

      uni.showToast({
        title: isFavoriteLocal.value ? '收藏成功' : '取消收藏成功',
        icon: 'success',
      })

      // 重新获取数据以确保服务器状态与本地状态一致
      setTimeout(() => {
        refetch()
      }, 500)
    }
    else {
      console.error('API返回失败:', data)
      uni.showToast({
        title: '操作失败',
        icon: 'error',
      })
    }
  },
  onError: (error: any) => {
    console.error('收藏操作失败:', error)
    console.log('错误详情:', error)

    // 恢复本地状态到操作前的状态
    // 注意：这里我们无法直接获取previousState，所以使用简单的切换
    isFavoriteLocal.value = !isFavoriteLocal.value
    console.log('恢复状态到:', isFavoriteLocal.value)

    // 检查是否是401错误（token过期）
    if (error?.statusCode === 401) {
      uni.showToast({
        title: '登录信息已过期，请重新登录',
        icon: 'none',
        duration: 2000,
      })
    }
    else {
      uni.showToast({
        title: '操作失败',
        icon: 'error',
      })
    }
  },
})

// 注意：现在使用同一个addFavorite接口来处理收藏和取消收藏

// 切换收藏状态
function toggleFavorite() {
  if (!productDetail.value?.data)
    return

  console.log('当前收藏状态:', isFavoriteLocal.value)
  console.log('产品ID:', productDetail.value.data.productId)

  // 记录操作前的状态，用于错误恢复
  const previousState = isFavoriteLocal.value

  if (isFavoriteLocal.value) {
    // 取消收藏
    console.log('执行取消收藏操作')
    addFavorite({
      params: {
        productId: productDetail.value.data.productId,
        action: 'remove',
      },
    })
  }
  else {
    // 添加收藏
    console.log('执行添加收藏操作')
    addFavorite({
      params: {
        productId: productDetail.value.data.productId,
        action: 'add',
      },
    })
  }
}

// 分享功能
function shareProduct() {
  uni.showActionSheet({
    itemList: ['分享给朋友', '分享到朋友圈'],
    success: (res) => {
      if (res.tapIndex === 0) {
        uni.showToast({ title: '分享给朋友', icon: 'success' })
      }
      else if (res.tapIndex === 1) {
        uni.showToast({ title: '分享到朋友圈', icon: 'success' })
      }
    },
  })
}

// 购买直达
function goToPurchase() {
  if (!productDetail.value?.data)
    return

  const { directType, directLink } = productDetail.value.data

  if (directType === 0 && directLink) {
    // 网址类型 - 复制链接到剪贴板
    uni.setClipboardData({
      data: directLink,
      success: () => {
        uni.showToast({
          title: '购买链接已复制',
          icon: 'success',
        })
        // 尝试在浏览器中打开
        // #ifdef H5
        window.open(directLink, '_blank')
        // #endif
        // #ifdef MP-WEIXIN
        uni.showModal({
          title: '购买直达',
          content: '链接已复制到剪贴板，请在浏览器中打开',
          showCancel: false,
        })
        // #endif
      },
      fail: () => {
        uni.showToast({
          title: '复制失败',
          icon: 'error',
        })
      },
    })
  }
  else if (directType === 1 && directLink) {
    // 手机号类型
    uni.makePhoneCall({
      phoneNumber: directLink,
    })
  }
  else {
    uni.showToast({
      title: '暂无购买链接',
      icon: 'none',
    })
  }
}

// 获取安全等级颜色
function getSafetyLevelColor(level: string) {
  const colors = {
    A: '#4CAF50', // 绿色
    B: '#4CAF50', // 绿色
    C: '#FF9800', // 橙色
    D: '#FF9800', // 橙色
    E: '#F44336', // 红色
  }
  return colors[level as keyof typeof colors] || '#9E9E9E'
}

// 获取安全等级描述
function getSafetyLevelDesc(level: string) {
  const descs = {
    A: '大幅度优于国标要求，单项指标均符合国标限定，综合指标比限定值低60%以上',
    B: '显著优于国标要求，单项指标均符合国标限定，综合指标比限定值低30%以上',
    C: '略优于国标要求，单项指标均符合国标限定，综合指标比限定值低15%以上',
    D: '符合国标要求，单项指标均符合国标限定，综合指标低于限定值',
    E: '不符合国家标准，至少有一项指标不符合国标限定，产品将被退回厂商，不允许上架',
  }
  return descs[level as keyof typeof descs] || '未知等级'
}

// 获取完整图片URL
function getFullImageUrl(relativePath: string) {
  if (!relativePath)
    return '/static/images/default-avatar.png'
  if (relativePath.startsWith('http'))
    return relativePath
  const ossBaseUrl = 'https://oss.tz-group.com/'
  const cleanPath = relativePath.startsWith('/') ? relativePath.slice(1) : relativePath
  return `${ossBaseUrl}${cleanPath}`
}

// 跳转到科普页面
function goToScience() {
  uni.navigateTo({ url: '/pages/quality/index' })
}
</script>

<template>
  <view class="product-detail-page">
    <!-- 加载状态 -->
    <view v-if="isLoading" class="h-96 flex items-center justify-center">
      <text class="text-gray-500">
        加载中...
      </text>
    </view>

    <!-- 错误状态 -->
    <view v-else-if="error" class="h-96 flex items-center justify-center">
      <text class="text-red-500">
        加载失败，请重试
      </text>
    </view>

    <!-- 产品详情内容 -->
    <view v-else-if="productDetail?.data" class="pb-20">
      <!-- 产品主信息区 -->
      <view class="mb-4 bg-white p-4">
        <!-- 产品图片 -->
        <view class="mb-4 flex justify-center">
          <image
            v-if="productDetail.data.mainPhotoes?.[0]?.attachmentAddress"
            :src="getFullImageUrl(productDetail.data.mainPhotoes[0].attachmentAddress)"
            class="max-h-80 max-w-full rounded-lg"
            mode="aspectFit"
          />
          <view v-else class="h-64 w-64 flex items-center justify-center rounded-lg bg-gray-200">
            <text class="text-gray-400">
              暂无图片
            </text>
          </view>
        </view>

        <!-- 产品名称 -->
        <view class="mb-2 text-center">
          <text class="text-xl text-gray-800 font-bold">
            {{ productDetail.data.productName }}
          </text>
        </view>

        <!-- 品牌产地 -->
        <view class="mb-4 text-center">
          <text class="text-gray-600">
            {{ productDetail.data.brand }} {{ productDetail.data.model }}
          </text>
        </view>

        <!-- 等级认证信息 -->
        <view v-if="productDetail.data.identityData" class="mb-4">
          <view class="mb-2 flex items-center justify-between">
            <text class="text-lg font-medium">
              {{ productDetail.data.identityData.gradeName || '等级认证' }}
            </text>
            <view class="flex items-center">
              <text class="mr-2 text-sm text-gray-500">
                {{ productDetail.data.identityData.gb || '国标' }}
              </text>
              <view class="h-8 w-8 flex items-center justify-center rounded-full bg-green-100">
                <text class="i-carbon-checkmark text-sm text-green-600" />
              </view>
            </view>
          </view>

          <!-- 等级显示 -->
          <view class="mb-2 flex items-center">
            <view class="flex flex-1">
              <view
                v-for="level in ['A', 'B', 'C', 'D', 'E']"
                :key="level"
                class="h-8 flex flex-1 items-center justify-center text-sm text-white font-medium"
                :style="{
                  backgroundColor:
                    level === productDetail.data.identityData?.grade
                      ? getSafetyLevelColor(level)
                      : '#E0E0E0',
                }"
              >
                {{ level }}
              </view>
            </view>
          </view>

          <!-- 等级描述 -->
          <view class="mb-2 text-sm text-gray-600">
            {{ getSafetyLevelDesc(productDetail.data.identityData.grade || '') }}
          </view>

          <!-- 生产厂商 -->
          <view v-if="productDetail.data.identityData.storeName" class="mb-2 text-sm text-gray-600">
            生产厂商：{{ productDetail.data.identityData.storeName }}
          </view>

          <!-- 分级标准 -->
          <view
            v-if="productDetail.data.identityData.gradeStandard"
            class="mb-2 text-sm text-gray-600"
          >
            分级标准：{{ productDetail.data.identityData.gradeStandard }}
          </view>
        </view>
      </view>

      <!-- 指标科普区 -->
      <view v-if="productDetail.data.targetScienceData" class="mb-4 bg-white p-4">
        <view class="mb-4 text-lg font-medium">
          {{ productDetail.data.targetScienceData.scienceName || '指标科普' }}
        </view>

        <!-- 科普简介 -->
        <view
          v-if="productDetail.data.targetScienceData.introduction"
          class="mb-4 text-sm text-gray-600"
        >
          {{ productDetail.data.targetScienceData.introduction }}
        </view>

        <!-- 科普封面图片 -->
        <view v-if="productDetail.data.targetScienceData.covers?.length" class="mb-4">
          <view class="grid grid-cols-2 gap-2">
            <view
              v-for="(cover, index) in productDetail.data.targetScienceData.covers"
              :key="index"
              class="aspect-square overflow-hidden rounded-lg bg-gray-100"
            >
              <image
                :src="getFullImageUrl(cover.attachmentAddress)"
                class="h-full w-full"
                mode="aspectFill"
              />
            </view>
          </view>
        </view>

        <!-- 科普附件 -->
        <view v-if="productDetail.data.targetScienceData.attachments?.length" class="mb-4">
          <view class="mb-2 text-sm font-medium">
            相关附件
          </view>
          <view class="space-y-2">
            <view
              v-for="(attachment, index) in productDetail.data.targetScienceData.attachments"
              :key="index"
              class="flex items-center rounded-lg bg-gray-50 p-3"
            >
              <text class="i-carbon-document mr-2 text-lg text-gray-500" />
              <text class="flex-1 text-sm text-gray-700">
                {{ attachment.attachmentName }}
              </text>
            </view>
          </view>
        </view>
      </view>

      <!-- 商品详情区 -->
      <view class="mb-4 bg-white p-4">
        <view class="mb-4 text-lg font-medium">
          商品详情
        </view>

        <!-- 产品介绍图片 -->
        <view v-if="productDetail.data.productData?.introductionPhotoes?.length" class="mb-6">
          <view class="space-y-3">
            <view
              v-for="(image, index) in productDetail.data.productData.introductionPhotoes"
              :key="index"
              class="overflow-hidden rounded-lg"
            >
              <image
                :src="getFullImageUrl(image.attachmentAddress)"
                class="w-full"
                mode="widthFix"
              />
            </view>
          </view>
        </view>

        <!-- 如果没有产品介绍图片，显示默认内容 -->
        <view v-else class="mb-6 text-center text-gray-500">
          <text class="i-carbon-image mb-2 block text-4xl" />
          <text class="text-sm">
            暂无产品介绍图片
          </text>
        </view>
      </view>

      <!-- 检测溯源区 -->
      <view v-if="productDetail.data.inspectionData" class="mb-4 bg-white p-4">
        <view class="mb-4 text-lg font-medium">
          检测溯源
        </view>

        <!-- 检测基本信息 -->
        <view class="mb-4 space-y-2">
          <view v-if="productDetail.data.inspectionData.gb" class="flex justify-between">
            <text class="text-gray-600">
              基础国标：
            </text>
            <text class="text-gray-800">
              {{ productDetail.data.inspectionData.gb }}
            </text>
          </view>
          <view v-if="productDetail.data.inspectionData.gradeStandard" class="flex justify-between">
            <text class="text-gray-600">
              分级标准：
            </text>
            <text class="text-gray-800">
              {{ productDetail.data.inspectionData.gradeStandard }}
            </text>
          </view>
          <view
            v-if="productDetail.data.inspectionData.inspectionOrganization"
            class="flex justify-between"
          >
            <text class="text-gray-600">
              检测机构：
            </text>
            <text class="text-gray-800">
              {{ productDetail.data.inspectionData.inspectionOrganization }}
            </text>
          </view>
          <view
            v-if="productDetail.data.inspectionData.inspectionTime"
            class="flex justify-between"
          >
            <text class="text-gray-600">
              检测时间：
            </text>
            <text class="text-gray-800">
              {{ productDetail.data.inspectionData.inspectionTime }}
            </text>
          </view>
          <view
            v-if="productDetail.data.inspectionData.inspectionAddress"
            class="flex justify-between"
          >
            <text class="text-gray-600">
              检测地点：
            </text>
            <text class="text-gray-800">
              {{ productDetail.data.inspectionData.inspectionAddress }}
            </text>
          </view>
        </view>

        <!-- 检测附件 -->
        <view v-if="productDetail.data.inspectionData.attachments?.length" class="mb-4">
          <view class="mb-2 text-sm font-medium">
            检测报告
          </view>
          <view class="space-y-2">
            <view
              v-for="(attachment, index) in productDetail.data.inspectionData.attachments"
              :key="index"
              class="flex items-center rounded-lg bg-gray-50 p-3"
            >
              <text class="i-carbon-document mr-2 text-lg text-gray-500" />
              <text class="flex-1 text-sm text-gray-700">
                {{ attachment.attachmentName }}
              </text>
            </view>
          </view>
        </view>
      </view>

      <!-- 科普视频区 -->
      <view v-if="productDetail.data.scienceVideoData" class="mb-4 bg-white p-4">
        <view class="mb-4 text-lg font-medium">
          {{ productDetail.data.scienceVideoData.scienceName || '科普视频' }}
        </view>

        <!-- 视频简介 -->
        <view
          v-if="productDetail.data.scienceVideoData.introduction"
          class="mb-4 text-sm text-gray-600"
        >
          {{ productDetail.data.scienceVideoData.introduction }}
        </view>

        <!-- 视频封面 -->
        <view v-if="productDetail.data.scienceVideoData.covers?.length" class="mb-4">
          <view class="grid grid-cols-2 gap-2">
            <view
              v-for="(cover, index) in productDetail.data.scienceVideoData.covers"
              :key="index"
              class="aspect-video overflow-hidden rounded-lg bg-gray-100"
            >
              <image
                :src="getFullImageUrl(cover.attachmentAddress)"
                class="h-full w-full"
                mode="aspectFill"
              />
            </view>
          </view>
        </view>

        <!-- 视频附件 -->
        <view v-if="productDetail.data.scienceVideoData.attachments?.length" class="mb-4">
          <view class="mb-2 text-sm font-medium">
            视频资源
          </view>
          <view class="space-y-2">
            <view
              v-for="(attachment, index) in productDetail.data.scienceVideoData.attachments"
              :key="index"
              class="flex items-center rounded-lg bg-gray-50 p-3"
            >
              <text class="i-carbon-play mr-2 text-lg text-gray-500" />
              <text class="flex-1 text-sm text-gray-700">
                {{ attachment.attachmentName }}
              </text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view
      class="fixed bottom-0 left-0 right-0 flex items-center border-t border-gray-200 bg-white p-4"
    >
      <view class="flex flex-1 justify-around">
        <view class="flex flex-col items-center" @click="goToScience">
          <text class="i-carbon-book mb-1 text-lg text-gray-600" />
          <text class="text-xs text-gray-600">
            科普
          </text>
        </view>
        <view class="flex flex-col items-center">
          <text class="i-carbon-target mb-1 text-lg text-gray-600" />
          <text class="text-xs text-gray-600">
            溯源
          </text>
        </view>
        <view class="flex flex-col items-center" @click="toggleFavorite">
          <text
            :class="
              isFavoriteLocal
                ? 'i-carbon-star-filled text-yellow-500'
                : 'i-carbon-star text-gray-600'
            "
            class="mb-1 transform text-lg transition-all duration-300 hover:scale-110"
          />
          <text class="text-xs text-gray-600 transition-colors duration-300">
            {{ isFavoriteLocal ? '已收藏' : '收藏' }}
          </text>
        </view>
        <view class="flex flex-col items-center" @click="shareProduct">
          <text class="i-carbon-share mb-1 text-lg text-gray-600" />
          <text class="text-xs text-gray-600">
            分享
          </text>
        </view>
      </view>
      <button class="ml-4 rounded-lg bg-orange-500 px-6 py-3 text-white" @click="goToPurchase">
        购买直达
      </button>
    </view>
  </view>
</template>

<style scoped>
.product-detail-page {
  background-color: #f5f5f5;
  min-height: 100vh;
}
</style>
